package v1

import (
	"fmt"
	"usplatformserver/global"
	"usplatformserver/internal/model"
	"usplatformserver/internal/service"
	"usplatformserver/pkg/app"
	"usplatformserver/pkg/errcode"

	"github.com/gin-gonic/gin"
)

type GradingStandard struct{}

// 评级标准获取结果
type gradingStandardRet struct {
	GradingStd *model.GradingStd
	Err        error
}

func NewGradingStandard() GradingStandard {
	return GradingStandard{}
}

// @Summer 获取甲状腺评级标准
// @Produce json
// @Param organType query int true "检查部位"
// @Success 200 {object} model.GradingStdSwaggerSuccess "成功"
// @Failure 400 {object} errcode.Error "请求错误"
// @Failure 500 {object} errcode.Error "内部错误"
// @Router /api/v1/grading/standard [get]
func (t *GradingStandard) GetGradingStandard(c *gin.Context) {
	getChan := make(chan gradingStandardRet, 1)

	param := service.GradingStdRequest{}
	response := app.NewResponse(c)
	valid, errs := app.BindAndValid(c, &param)
	if !valid {
		response.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
		return
	}

	go func() {

		addr := fmt.Sprintf("tcp://%v:%d", global.ZMQSettings.Addr, global.ZMQSettings.Port)
		var ret gradingStandardRet
		svc := service.New(c.Request.Context())
		gradingStd, err := svc.GetGradingStd(addr, *param.OrganType)
		ret.Err = err
		ret.GradingStd = gradingStd
		getChan <- ret
	}()

	for {
		ret := <-getChan
		if ret.Err != nil {
			global.Logger.Infof("svc.GetGradingStandard failed: %v", ret.Err)
			response := app.NewResponse(c)
			response.ToErrorResponse(errcode.ErrorGetGradingStandardFail)
			break
		} else {
			response := app.NewResponse(c)
			response.ToResponse(ret.GradingStd)
			break
		}
	}
	close(getChan)
}
